package com.dao.impl;

import com.dao.BaseDao;
import com.dao.UserDao;
import com.entity.User;
import com.util.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public class UserDaoImpl implements BaseDao<User> {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public int selectByName(String name,String password){
        String sql = "select count(1) from user where email = ? and password=?";
        //sql，返回结果的类型，两个占位符的参数
        return jdbcTemplate.queryForObject(sql, Integer.class,name,password);
    }

    @Override
    public List<User> selectAll() {
        String sql = "select * from user";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        List<User> list = jdbcTemplate.query(sql,rowMapper);
        return list;
    }

    @Override
    public User selectById(String id) {
        String sql = "select * from user where id = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql,rowMapper,id);
        return user;
    }

    @Override
    public boolean insertUser(User user) {
        String sql = "insert into user values(?,?,?,?)";
        int cout=jdbcTemplate.update(sql,IDUtil.getId(),user.getEmail(),user.getPassword(),new Date());
        return cout>0;
    }

    @Override
    public boolean deleteById(String id) {
        String sql = "delete from user where id = ?";
        int count = jdbcTemplate.update(sql,id);
        return count>0;
    }

    @Override
    public boolean update(User user) {
        String sql = "update user set email = ? and password =? where id = ?";
        int count = jdbcTemplate.update(sql,user.getEmail(),user.getPassword(),user.getId());
        return count>0;
    }
}
